<?php

namespace App\Console\Commands;

use App\Http\Models\Record;
use App\Http\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class CalcInterest extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'calc:interest';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $users = User::where('money', '>', 0)->where('is_disabled', 0)->get();
        DB::beginTransaction();
        try {
            foreach ($users as $user) {
                $per = 0;
                switch ($user->level_id) {
                    case 2:
                        $per = 0.03;
                        break;
                    case 3:
                        $per = 0.05;
                        break;
                    case 4:
                        $per = 0.07;
                        break;
                    default:
                        break;
                } 
                if($per > 0) {
                    $addMoney = $user->money * $per;
                    $user->money = $user->money + $addMoney;
                    $user->save();
                    Record::create([
                        'id_user' => $user->id_wechat,
                        'body_name' => '本金锁仓利息',
                        'body_direction' => 1,
                        'body_stake' => $addMoney
                    ]);
                }
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
        }
    }
}
